<template>
	<view class="red-pkg">
		<!-- 0，提示 -->
		<view class="top-tips">
			<text>{{topTips}}</text>
		</view>

		<!-- 1，头部信息 -->
		<red-head v-if="!isShowUser" :activeIndex="activeIndex" @changeActive="changeActive"></red-head>

		<!-- 2，主要内容 -->
		<!-- 2.1，单个金额输入金额 -->
		<view v-if="isShowUser">
			<view class="con">
				<view class="con-left">
					<text class="con-left-amount">单个金额</text>
				</view>
				<view class="con-right">
					<input @input="inputCheck" type="digit" placeholder="￥0.00" class="con-right-input"
						v-model="amount" />
				</view>
			</view>
			<view class="con con-title">
				<input type="text" placeholder="￥恭喜发财,大吉大利" v-model="detail" />
			</view>
		</view>
		<!-- 2.2，群聊发送 -->
		<view v-else>
			<view class="con" v-if="activeIndex == 1 || activeIndex == 2">
				<view class="con-left">
					<text class="con-left-title">红包个数</text>
				</view>
				<view class="con-right">
					<input type="number" placeholder="0" @input="inputPkgNum" clearable class="con-right-input"
						v-model="pkgNum" />

					<text>个</text>
				</view>
			</view>

			<view class="con">
				<view class="con-left">
					<text class="con-left-title" v-if="activeIndex == 2">单个金额</text>
					<text class="con-left-title" v-else>总金额</text>
				</view>
				<view class="con-right">
					<input @input="inputCheck" type="digit" placeholder="￥0.00" class="con-right-input"
						v-model="amount" />
				</view>
			</view>

			<view class="con" v-if="activeIndex == 3">
				<view class="con-left">
					<text class="con-left-title">发给谁</text>
				</view>
				<view class="con-right" @click="showGroupUser">
					<view class="con-right-text">
						<text>{{sendUserName}}</text>
					</view>
					<view class="con-right-img">
						<image :src="require('@/static/img/common/goMore_1.svg')"></image>
					</view>
				</view>
			</view>

			<view class="con con-title">
				<input type="text" placeholder="￥恭喜发财,大吉大利" v-model="detail" />
			</view>
		</view>

		<!-- 3，价格发送框 -->
		<view class="price">
			<view v-if="activeIndex == 2">￥{{amount == '' ? '0.00': getPrice(amount * pkgNum)}}</view>
			<view v-else>￥{{amount == '' ? '0.00': getPrice(amount)}}</view>
		</view>
		<view @click="sendMsg" class="btn" :style="{'background-color' : amount == '' ?'#DD4A4D':'#F85351'}">
			<text>塞钱红包</text>
		</view>

		<!-- 4， -->
		<view class="bottom-tips">
			<text>未领取的红包，将于24小时后发起退款</text>
		</view>

		<!-- 5，支付键盘 -->
		<pay-pop txt="支付密码" :pwdlength="6" ref="pay_pop" @pwd_e="pwdSend"></pay-pop>

		<!-- 6，群成员 -->
		<red-user @selectUser="selectUser" :isShowUser="isShowGroupUser" @display="closeGroupUser"
			:groupUsers="groupUserList"></red-user>
	</view>
</template>

<script>
	import redHead from './child/red-head.vue'
	import payPop from '@/components/apk/pay-pop/pay-pop.vue'
	import redUser from './child/red-user.vue'

	import {
		getNowTime
	} from '@/utils/time/time.js'

	import {
		queryBalance
	} from '@/api/http/main/my/pay.js'
	import {
		sendPkg
	} from '@/api/http/msg/redpkg.js'

	import {
		queryGroupUsers
	} from '@/api/http/msg/group.js'

	import {
		handlePrice
	} from '@/utils/price.js'

	export default {
		components: {
			redHead,
			payPop,
			redUser
		},
		data() {
			return {
				amount: '',
				firstName: '￥',
				detail: '',
				isShowUser: false,
				pkgNum: '',
				activeIndex: 1,
				activeType: '2', //默认拼手气红包

				msgObjectData: {},
				userId: uni.getStorageSync('userId'),
				head: uni.getStorageSync('head'),
				nickname: uni.getStorageSync('nickname'),

				isShow: false,
				isShowGroupUser: false,
				groupUserList: [],
				sendUserName: '选择发送对象',
				selectSendUser: {},
				topTips: '红包个数不能超过当前群聊人数'
			}
		},
		computed: {
			// fullName: {
			// 	get: function() {
			// 		if ((this.firstName + this.amount).length <= 1) {
			// 			return this.amount
			// 		}
			// 		return this.firstName + this.amount
			// 	},
			// 	set: function(value) {
			// 		//清除之前的‘￥’
			// 		value = value.replace(/￥/g, '')
			// 		//value = value.replace( /^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3" )
			// 		this.amount = value
			// 	}
			// }
		},
		methods: {
			inputPkgNum(e) {
				const v = e.detail.value
				this.pkgNum = '1'

				const zero = /^(0{2,})|[^0-9]/g
				let final = 0
				if (!v) {
					final = 0
				} else {
					final = v.toString().replace(zero, (v) => {
						return 0
					})

					if (final.split('')[0] * 1 === 0) {
						final = final.slice(1) - 0 || 0
					}
				}
				this.$nextTick(() => {
					this.pkgNum = final.toString() || '0'
				})
			},

			getPrice(price) {
				var p = handlePrice(price)
				//console.log(p)
				return p
			},
			inputCheck(e) {
				//正则表达试
				e.target.value = e.target.value.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				//重新赋值给input
				this.$nextTick(() => {
					this.amount = e.target.value;
				});
			},

			changeActive(id, item) {
				this.activeIndex = id
				if (!item) {
					this.activeIndex = id
				} else {
					this.activeIndex = item.id
					this.activeType = item.type
				}

			},
			// changeInput(){
			// 	this.amount = this.amount.replace( /^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3" )
			// },
			sendMsg() {
				var that = this

				if (that.activeIndex != 3 && that.msgObjectData.type == 3 && (this.amount == '' || this.pkgNum == '')) {
					return uni.$showMsg('参数输入异常！');
				}

				if (that.activeIndex == 3 && that.msgObjectData.type == 3 && this.amount == '') {
					return uni.$showMsg('参数输入异常！');
				}

				if (that.msgObjectData.type == 2 && this.amount == '') {
					return uni.$showMsg('参数输入异常！');
				}

				var reg = /^[\d|\.]*$/;
				if (!reg.test(this.amount)) {
					return uni.$showMsg('金额输入异常！');
				}

				if (parseFloat(this.amount) <= 0) {
					return uni.$showMsg('金额异常！');
				}

				//金额大小判断
				if (that.msgObjectData.type == 2 && parseFloat(this.amount) > 200) {
					return uni.$showMsg('最多只能发送200元红包！');
				}

				if (that.msgObjectData.type == 3 && (parseFloat(this.amount) / this.pkgNum) < 0.01) {
					return uni.$showMsg('金额和红包个数分配异常！');
				}

				if (that.activeIndex == 3 && JSON.stringify(that.selectSendUser) == "{}") {
					return uni.$showMsg('请选择指定对象！');
				}


				queryBalance().then(res => {
					if (res.data.pubInfo.code !== 0) {
						return uni.$showMsg(res.data.pubInfo.message);
					}
					//查询余额
					var reqAmount = 0
					if (this.activeIndex == 2) {
						//普通红包
						reqAmount = parseFloat(that.amount * that.pkgNum)
					} else {
						reqAmount = parseFloat(that.amount)
					}

					var balance = res.data.busInfo
					if (reqAmount > balance) {
						return uni.$showMsg('您的余额不足！请先充值');
					}

					//输入密码
					that.$refs.pay_pop.Open()

				})
			},
			pwdSend(e) {
				//console.log(e)
				var that = this
				var req = {}
				var reqAmount = 0;
				if (this.activeIndex == 2) {
					//普通红包
					reqAmount = parseFloat(that.amount * that.pkgNum)
				} else {
					reqAmount = parseFloat(that.amount)
				}

				if (that.msgObjectData.type == 2) {
					req = {
						amount: reqAmount,
						title: that.detail || '恭喜发财，大吉大利',
						hbType: '4',
						pwd: e,
						num: 1
					}
				} else if (that.activeIndex == 3) {
					//专属红包
					req = {
						amount: reqAmount,
						num: 1,
						title: that.detail || '恭喜发财，大吉大利',
						hbType: that.activeType,
						pwd: e,
						appointUserId: that.selectSendUser.userId,
						appointUserName: that.selectSendUser.nickname
					}
				} else {
					req = {
						amount: reqAmount,
						num: that.pkgNum,
						title: that.detail || '恭喜发财，大吉大利',
						hbType: that.activeType,
						pwd: e
					}
				}

				//判断密码是否输入正确
				sendPkg(req).then(res => {
					if (res.data.pubInfo.code !== 0) {
						return uni.$showMsg(res.data.pubInfo.message);
					}
					//返回得到红包id
					var redPkgId = res.data.busInfo

					//获取当前时间
					var nowTime = getNowTime() + ''

					//好友红包
					if (that.msgObjectData.type == 2) {
						//组装红包消息
						var redPkgMsg = {
							amount: parseFloat(reqAmount),
							num: 1,
							title: that.detail,
							hbType: '4'
						}

						let msgData = {
							type: that.$chatType.CHAT_FRIEND,
							msg: {
								senderId: that.userId,
								senderHead: that.head, //头像
								types: '4', //消息类型 （0文本，1图片连接，2音频，3地图）
								message: JSON.stringify(redPkgMsg), //消息 
								time: nowTime,
								tip: 0,
								receiverId: that.msgObjectData.id + '',
								receiverHead: that.msgObjectData.head,
								receiverName: that.msgObjectData.nickname,
								senderName: that.nickname,
								redPkgId: redPkgId
							}
						}

						uni.myWebsocket.socketTask.send({
							data: JSON.stringify(msgData),
							async success() {
								//返回上一页
								return uni.navigateBack(1)
							},
							fail(e) {
								uni.$showMsg('发送失败！');
								//this.connectSocketInit()
							}
						});
					}

					//群聊发红包
					if (that.msgObjectData.type == 3) {
						//组装红包消息
						/* var redPkgMsg = {
							amount: parseFloat(that.amount),
							num: parseInt(that.pkgNum),
							title: that.detail,
							hbType: that.activeType,
							
						} */
						var redPkgMsg = req
						redPkgMsg.pwd = ''

						//组装请求参数
						let msgData = {
							type: that.$chatType.CHAT_GROUP,
							msg: {
								groupId: that.msgObjectData.id,
								senderId: that.userId,
								types: 4, //消息类型 （0文本，1图片连接，2音频，3地图，4红包）
								message: JSON.stringify(redPkgMsg), //消息 
								time: getNowTime() + '',
								groupHead: that.msgObjectData.head,
								groupName: that.msgObjectData.nickname,
								senderHead: that.head,
								senderName: that.nickname,
								state: 0,
								tip: 0,
								redPkgId: redPkgId
							}
						}

						uni.myWebsocket.socketTask.send({
							data: JSON.stringify(msgData),
							async success() {
								console.log(that.msgObjectData)
								// return uni.switchTab({
								// 	url: '/pages/newMsg/chat-group/chat-group?msgObject=' +
								// 		JSON.stringify(that.msgObjectData),
								// 	success: () => {
								// 		//plus.navigator.closeSplashscreen();
								// 	}
								// })
								//返回上一页
								return uni.navigateBack(1)
							},
							fail(e) {
								uni.$showMsg('发送失败！');
							}
						});

					}

				})
			},
			connectSocketInit() {
				uni.myWebsocket = ''
				if (uni.myWebsocket == undefined || uni.myWebsocket == '' || uni.myWebsocket == null) {
					//连接上websocket
					uni.$connectSocketInit.connectSocket(uni.$basePort)
				}
			},
			getGroupUsers() {
				queryGroupUsers(this.msgObjectData.id, '', '', '1').then(res => {
					if (res.data.pubInfo.code !== 0) {
						return uni.$showMsg(res.data.pubInfo.message);
					}
					this.groupUserList = res.data.busInfo

				})
			},

			//展开用户选择框
			showGroupUser() {
				this.getGroupUsers()
				this.isShowGroupUser = true
			},
			//关闭选择用户弹框
			closeGroupUser() {
				this.isShowGroupUser = false
			},
			selectUser(item) {
				//console.log(item)
				this.sendUserName = item.nickname
				this.selectSendUser = item
				this.isShowGroupUser = false
			}
		},
		onLoad(e) {
			var msgObject = JSON.parse(e.msgObject)
			if (msgObject.type == 2) {
				this.isShowUser = true
			}
			this.msgObjectData = msgObject
			//console.log(msgObject)

			this.connectSocketInit()

			//this.getGroupUsers()
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #EDEDED;
	}

	.top-tips {
		width: 100%;
		text-align: center;
		background-color: #B79F67;
		height: 60rpx;
		line-height: 60rpx;

		text {
			font-size: 22rpx;
			color: #fff;
		}
	}

	.red-pkg {
		width: 100%;
	}

	input {
		font-size: 32rpx;
	}

	.con {
		width: 86%;
		padding: 10rpx 3%;
		background-color: #fff;
		border-radius: 20rpx;
		display: flex;
		justify-content: space-between;
		height: 100rpx;
		line-height: 100rpx;
		margin: 0 0 40rpx 4%;
		font-size: 32rpx;

		.con-left {
			flex: 1;
		}


		.con-left-amount {
			color: #D18076;
		}

		.con-right-input {
			height: 80rpx;
			line-height: 80rpx;
			margin-top: 10rpx;
			text-align: right;

		}

		.con-right {
			display: flex;
			flex: 1;
			justify-content: right;

			.con-right-text {
				line-height: 100rpx;

				text {
					font-size: 28rpx;
					color: rgba(166, 166, 166, 1);
				}
			}

			.con-right-img {
				image {
					width: 40rpx;
					height: 40rpx;
					margin-top: 30rpx;
				}
			}
		}

	}

	.con-title {
		input {
			margin-top: 10rpx;
			height: 80rpx;
			line-height: 80rpx;
			width: 100%;
		}
	}

	.price {
		height: 150rpx;
		line-height: 150rpx;
		text-align: center;
		font-size: 45rpx;
	}

	.btn {
		width: 60%;
		height: 80rpx;
		border-radius: 40rpx;
		margin-left: 20%;
		text-align: center;
		line-height: 80rpx;

		text {
			color: #fff;
			font-size: 32rpx;
		}
	}

	.bottom-tips {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		position: fixed;
		bottom: 0;
		text-align: center;

		text {
			font-size: 26rpx;
			color: #979797;
		}
	}
</style>